"use strict";

const crypto = require("crypto");

module.exports = {
    /**
     * md5加密字符串
     * @param {string} param 传入值
     */
    toMD5(param) {
        return crypto.createHash("md5").update(`${param}`).digest("hex");
    },
    /**
     * 把任意值转化为数字的方法
     * @param {any} val 任意值
     * @return {number} 返回值
     */
    toInt(val) {
        return parseInt(val, 10) || 0;
    },
    /**
     * 生成n位数字的方法
     * @param {number} len 生成随机数位数
     * @return {string} 返回生成的随机数字符串
     */
    createNum(len = 6) {
        let num = "";
        for (let i = 0; i < len; i++) {
            num += Math.ceil(Math.random() * 10);
        }
        return num;
    },
    /**
     * 小于10的数字前补0
     * @param {number} num 数字
     */
    toDouble(num) {
        return num < 10 ? `0${num}` : `${num}`;
    },
    /**
     * 格式化时间显示
     * @param {number} time 毫秒数
     */
    formatTime(time) {
        const yearBase = 365 * 24 * 60 * 60 * 1000;
        const dayBase = 24 * 60 * 60 * 1000;
        const hourBase = 60 * 60 * 1000;
        const minuteBase = 60 * 1000;
        const secondBase = 1000;
        const year = Math.floor(time / yearBase);
        const day = Math.floor(time % yearBase / dayBase);
        const hour = Math.floor(time % dayBase / hourBase);
        const minute = Math.floor(time % dayBase % hourBase / minuteBase);
        const second = Math.floor(time % dayBase % hourBase % minuteBase / secondBase);
        return `${year ? `${year}年` : ""}${day}天${this.toDouble(hour)}小时${this.toDouble(minute)}分钟${this.toDouble(second)}秒`;
    },
};
